package com.wiscamp.ninechapters.challenges.infrastructure.mappers;

import com.wiscamp.ninechapters.challenges.infrastructure.po.UserPointsWeekPO;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;

@Repository
public interface UserPointsWeekMapper extends JpaRepository<UserPointsWeekPO, Long>, JpaSpecificationExecutor<UserPointsWeekPO> {

    /**
     * 按个人年周积分排名分页获取前100名用户编号列表
     *
     * @param pageable
     * @return
     */

    @Query(value = "select e.userId from UserPointsWeekPO e where e.userId > 0 order by e.weekPoints desc")
    Page<Long> getTop100UserIdsSortByPoints(Pageable pageable);

    /**
     * 按个人年周积分排名分页获取前100名用户年周积分列表
     *
     * @param pageable
     * @return
     */

    @Query(value = "select e from UserPointsWeekPO e where e.dateYear = :dateYear and e.weekOfYear = :weekOfYear order by e.weekPoints desc")
    Page<UserPointsWeekPO> getTop100OrderByWeekPoints(int dateYear, int weekOfYear, Pageable pageable);

    @Query(value = "select e from UserPointsWeekPO e where e.userId = :userId and e.dateYear = :dateYear and e.weekOfYear = :weekOfYear")
    UserPointsWeekPO findByUserIdAndDateYearAndWeekOfYear(long userId, int dateYear, int weekOfYear);

    @Modifying
    @Transactional
    @Query(nativeQuery = true, value = "update user_points_week e set e.week_rank = 999 where e.week_rank <= 100 and e.user_id not in (:userIds)")
    void rankingAfter100ByPoints(Collection<Long> userIds);
}